package com.gimi.cloud.jimi.commonService.jiguang;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.common.enums.common.RedisKeyEnum;
import com.gimi.cloud.jimi.common.utils.HttpClientUtil;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.commonService.jiguang.param.Audience;
import com.gimi.cloud.jimi.commonService.jiguang.param.JiguangPushParam;
import com.gimi.cloud.jimi.commonService.jiguang.param.Options;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import org.apache.http.Header;
import org.apache.http.ParseException;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;


/**
 * 极光推送
 */
//TODO （需要测试IOS）
@Component
public class JiguangPushUtil {

    private final static Logger log = LoggerFactory.getLogger(JiguangPushUtil.class);

    private IRedisService iRedisService;

    @Autowired
    public JiguangPushUtil(IRedisService iRedisService) {
        this.iRedisService = iRedisService;
    }

    /**
     * 获取cid
     *
     * @param appKey
     * @param masterSecret
     * @return
     * @throws Exception
     */
    public static String getCid(String cidUrl, String appKey, String masterSecret) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        map.put("Authorization", getAuthorization(appKey, masterSecret));
        String result = HttpClientUtil.sendGet(cidUrl, null, map, null);
        JSONObject resultObject = JSON.parseObject(result);
        return resultObject.getJSONArray("cidlist").getString(0);
    }

    /**
     * 消息推送
     *
     * @param jsonParam
     * @param appKey
     * @param masterSecret
     * @throws ParseException
     * @throws IOException
     */
    public static String push(String url, String jsonParam, String appKey, String masterSecret) throws ParseException, IOException {
        BasicHeader basicHeader = new BasicHeader("Authorization", getAuthorization(appKey, masterSecret));
        List<Header> headerLists = new ArrayList<>();
        headerLists.add(basicHeader);
        return HttpClientUtil.sendPostJson(url, jsonParam, headerLists.toArray(new Header[headerLists.size()]));
    }

    /**
     * Authorization生成
     *
     * @param appKey
     * @param masterSecret
     * @return
     */
    private static String getAuthorization(String appKey, String masterSecret) {
        return "Basic " + java.util.Base64.getEncoder().encodeToString((appKey + ":" + masterSecret).getBytes());
    }

    /**
     * 推送消息给所有用户
     *
     * @param msg
     * @param extras 附加字段
     * @return
     * @throws Exception
     */
    public String pushAll(String msg, Map<String, Object> extras) throws Exception {
        JSONObject jsonConfig = iRedisService.getJSONObjectConfigByKey(RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + "app_jiguang_push");
        log.info("redis配置" + jsonConfig.toString());
        //配置详情见：https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/
        JiguangPushParam jiguangPushParam = new JiguangPushParam();
        jiguangPushParam.setCid(getCid(jsonConfig.getString("cidUrl"), jsonConfig.getString("appKey"), jsonConfig.getString("masterSecret")));
        jiguangPushParam.setAudience("all");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("alert", msg);
        if (extras != null && !extras.isEmpty()) {
            JSONObject object = new JSONObject();
            object.put("extras", extras);
            jsonObject.put("android", object);
            jsonObject.put("ios", object);
        }
        jiguangPushParam.setNotification(jsonObject);

        Options options = new Options();
        options.setApns_production(jsonConfig.getBoolean("environment"));
        jiguangPushParam.setOptions(options);
        String pushParam = JSON.toJSONString(jiguangPushParam);
        log.info("请求参数：" + pushParam);
        String resultStr = push(jsonConfig.getString("url"), pushParam, jsonConfig.getString("appKey"), jsonConfig.getString("masterSecret"));
        return resultStr;
    }

    /**
     * 根据用户别名推送消息
     *
     * @param msg    推送文本
     * @param extras 附加字段
     * @param alias  用户别名
     * @return
     * @throws Exception
     */
    public String pushAlias(String msg, Map<String, Object> extras, String... alias) throws Exception {
        JSONObject jsonConfig = iRedisService.getJSONObjectConfigByKey(RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + "app_jiguang_push");
        log.info("redis配置" + jsonConfig.toString());
        //配置详情见：https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/
        JiguangPushParam jiguangPushParam = new JiguangPushParam();
        jiguangPushParam.setCid(getCid(jsonConfig.getString("cidUrl"), jsonConfig.getString("appKey"), jsonConfig.getString("masterSecret")));

        Audience audience = new Audience();
        audience.setAlias(alias);

        jiguangPushParam.setAudience(audience);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("alert", msg);
        if (extras != null && !extras.isEmpty()) {
            JSONObject object = new JSONObject();
            object.put("extras", extras);
            jsonObject.put("android", object);
            jsonObject.put("ios", object);
        }
        jiguangPushParam.setNotification(jsonObject);

        Options options = new Options();
        options.setApns_production(jsonConfig.getBoolean("environment"));
        jiguangPushParam.setOptions(options);
        String pushParam = JSON.toJSONString(jiguangPushParam);
        log.info("请求参数：" + pushParam);
        String resultStr = push(jsonConfig.getString("url"), JSON.toJSONString(jiguangPushParam), jsonConfig.getString("appKey"), jsonConfig.getString("masterSecret"));
        log.info("返回值：" + resultStr);
        return resultStr;
    }
}
